package com.haieros.www.purerunshowsystem.service;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.Message;

import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.google.gson.Gson;
import com.haieros.www.purerunshowsystem.bean.MqTopIcRequestBean;
import com.haieros.www.purerunshowsystem.bean.MqTopIcResult;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by W520 on 2017/11/22.
 */

public class MQService extends Service {
    private int count = 0;
    private boolean threadDisable = false;

    private String host = "tcp://120.55.88.22:1883";
    //private String host = "tcp://192.168.0.113:1883";
    private String userName = "admin";
    private String passWord = "admin";
    private int i = 1;

    private MqttClient client;
    //    private String myTopic = "pureRun_test";
    // private String myTopic = "test/topic";
    private String myTopic;
    private MqttConnectOptions options;
    private ScheduledExecutorService scheduler;
    private String mTopIcUrl = "http://120.55.88.22:18080/pureRun/captureResources/getTopic";

    @Override
    public void onCreate() {
        super.onCreate();
//        init();
//        startReconnect();
        getMqTopic();

    }

    /**
     * 获取手机IMEI号
     */
    public static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            String imei = telephonyManager.getDeviceId();
            return imei;
        }


      return null;
    }
    public void getMqTopic()
    {
        OkHttpUtils
                .postString()
                .url(mTopIcUrl)
                .content(new Gson().toJson(new MqTopIcRequestBean("pureRunTV_test01", "AOC_TV")))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {

                        return response.body().string();

                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {
                        String msg= response.toString();
                        Log.e("TAG",msg);
                        Gson gson=new Gson();
                        MqTopIcResult mQBean=gson.fromJson(msg,MqTopIcResult.class);
                        myTopic=mQBean.getContent().getTopic();
                        Log.e("TAG","主题"+myTopic);
                        init();
                        startReconnect();
                        //开始下载
//                        downLoadVideo(videoBean.getContent().getUrl());
                    }
                });
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            scheduler.shutdown();
            client.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                if (!client.isConnected()) {
                    connect();
                }
            }
        }, 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }

    private void init() {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, myTopic,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
//                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------消息");
               Log.e("======","收到消息");
                    Intent intent = new Intent();
                    intent.putExtra("message", message.toString());
                    intent.putExtra("time","");
                    intent.setAction("com.haieros.www.purerunshowsystem.service.MQService");
                    sendBroadcast(intent);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void connect() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    client.connect(options);
                    Message msg = new Message();
                    msg.what = 2;
//                    System.out.println("连接成功");
//                    Log.i("链接成功","连接成功");
                    try {
                        client.subscribe(myTopic, 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("连接失败，系统正在重连");
                }
            }
        }).start();
    }
}
